
from init import PATHS
import logging
LOGGER = logging.getLogger(__name__)
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
matplotlib.style.use('seaborn')
import seaborn as sns
sns.set(style="white")
pal = sns.color_palette('colorblind')
from C_PatentVariables import conventions_names_colors
from E_Analysis import reading_datasets
dict_subsector_shortnames, dict_var_colors, list_of_subsectors_in_cleancars = conventions_names_colors.main()
import plotly.express as px


def main():
    LOGGER.info('Begin a_figures_maintext.py')
    # 1) OEM Patenting (Figures 2a,2b)
    OEMs_total_Bat_vs_FC()
    multiple_OEMS_share_Bat_minus_FC()
    # 2) Policy (Figures 3a,3c)
    plot_strategic_timelines()
    plot_rdd_data()
    plotting_meanOEM_patent_and_policyexposure_onsamegraph()
    # 3) Spillovers (Figures 4a (without Li-ion prices))
    # Battery and fuel cell patenting by sector
    plot_bat_fc_patenting_bysector()
    # Active suppliers (Figures 4b,4c)
    stackplot_activesupplierpatenting_bytype()
    plot_activesuppliers_stocks()
    LOGGER.info('End a_figures_maintext.py')



def OEMs_total_Bat_vs_FC():
    ts_counts = pd.read_csv(PATHS.dropbox / 'Data_outputted/C_PatentVariables/TimeSeries_FamilyCounts_in_ipc_cpc_transpo_from_OEM_and_Subsidiaries.csv')
    maskYears = ts_counts['earliest_filing_year'].isin(range(1990, 2016))
    fig, ax = plt.subplots()
    for var in ['Count_Bat_excl', 'Count_FC_excl']:
        plt.plot(ts_counts[maskYears]['earliest_filing_year'], ts_counts[maskYears][var], label=dict_var_colors[var][0], color=dict_var_colors[var][1], linewidth=3)
    plt.legend(ncol=1)
    plt.xlabel('Year')
    plt.ylabel('Number of Patent Families')
    plt.savefig(PATHS.figures / 'mainfigures' / 'patenting_total_OEM_Bat_v_FC.png', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / 'patenting_total_OEM_Bat_v_FC.pdf', bbox_inches='tight')
    plt.close()


def multiple_OEMS_share_Bat_minus_FC():
    dfoemyear = reading_datasets.read_oem_firmlevel_panel()
    dfoemyear['share_bat_excl'] = dfoemyear['Count_Bat_excl'] / dfoemyear['Count_CleanCar_excl']
    dfoemyear['share_fc_excl'] = dfoemyear['Count_FC_excl'] / dfoemyear['Count_CleanCar_excl']
    dfoemyear['diff_share_bat_fc_excl'] = dfoemyear['share_bat_excl'] - dfoemyear['share_fc_excl']
    var = 'diff_share_bat_fc_excl'
    maskYears = dfoemyear['earliest_filing_year'].isin(range(1990, 2016))
    dfoemyear['Count_BatFC_excl'] = dfoemyear['Count_FC_excl'] + dfoemyear['Count_Bat_excl']
    patentingintensity = dfoemyear[maskYears].groupby('shortname')['Count_BatFC_excl'].sum().sort_values(ascending=False)
    list_select = list(patentingintensity.index)[:7] + ['Tesla', 'Chery']
    # some OEMs only a few FC and Bat patents and the difference in share become very large because of that: only select OEMs with at least 10 Bat or FC patents over the period
    list_OEMs = list(patentingintensity[patentingintensity >= 10].index)
    for name in list_OEMs:
        mask1 = dfoemyear['shortname'] == name
        data = dfoemyear[maskYears & mask1][['earliest_filing_year', var]]
        if name in list_select:
            plt.plot(data['earliest_filing_year'], data[var], linewidth=2, label=name, color=pal[list_select.index(name)])
        else:
            plt.plot(data['earliest_filing_year'], data[var], color='0.8', linewidth=1)
    # add mean trend, weighted by clean car counts.
    dfoemyear['BatFC_weights'] = dfoemyear.groupby('earliest_filing_year')['Count_BatFC_excl'].transform(lambda x: x/x.sum())
    dfoemyear[f'weighted_{var}'] = dfoemyear['BatFC_weights'] * dfoemyear[var]
    wmean_trend = dfoemyear[maskYears].groupby('earliest_filing_year')[f'weighted_{var}'].sum()
    dfoemyear[maskYears][['OEM_Level1_ID', 'name', 'earliest_filing_year', 'Count_CleanCar_excl', var, 'Count_BatFC_excl', 'BatFC_weights', f'weighted_{var}']].sort_values(by='BatFC_weights', ascending=False)
    plt.plot(wmean_trend, linewidth=3, color='black', label='Mean OEM')
    plt.legend(ncol=5, loc='best', fontsize='small') ## legend too large again
    plt.xlabel('Year')
    plt.ylabel('Share Batteries - Share Fuel Cells')
    plt.savefig(PATHS.figures / 'mainfigures' / f'patenting_over_time_selectedOEMs_{var}.png', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / f'patenting_over_time_selectedOEMs_{var}.pdf', bbox_inches='tight')
    plt.close()


def plot_strategic_timelines():
    strategy = pd.read_csv(PATHS.dropbox / 'raw_data/PolicyLandscaping/country_tech_strategy_timeline_table.csv')
    strategy = strategy.rename(columns={'country': 'Country', 'strategy': 'Strategies'})
    strategy['Strategies'] = strategy['Strategies'].replace('Biofuels; nat gas', 'Biofuels or Natural Gas')
    strategy['start.date'] = strategy['start.date'].apply(lambda x: str(x) + '-01-01')
    strategy['end.date'] = strategy['end.date'].apply(lambda x: str(x) + '-01-01')
    palhex = pal.as_hex()
    color_map = {
        'BEV': palhex[0],
        'BEV with long-term plans for FCEV': palhex[-1],
        'All types': palhex[-3],
        'FCEV': palhex[3],
        'Biofuels or Natural Gas': palhex[2],
    }
    # legend_order = ['All types', 'BEV', 'BEV with long-term plans for FCEV', 'FCEV', 'Biofuels; nat gas']
    fig = px.timeline(strategy, x_start="start.date", x_end="end.date", y="Country", color="Strategies",
                      color_discrete_map=color_map)
    fig.update_layout(plot_bgcolor="white", legend=dict(yanchor="top", y=1))
    fig.write_image(PATHS.figures / 'mainfigures' / 'strategic_timelines.png', engine="kaleido")
    fig.write_image(PATHS.figures / 'mainfigures' / 'strategic_timelines.pdf', engine="kaleido")

def plot_rdd_data():
    df_rdd = reading_datasets.read_rdd_data()
    stackplot_rdd_data(df_rdd, tech_var='fchydrogen', figurename='PublicRDD_FCHyd')
    stackplot_rdd_data(df_rdd, tech_var='otherstorage', figurename='PublicRDD_OtherStorage')


def stackplot_rdd_data(df_rdd, tech_var, figurename):
    tech_var2 = 'Electric Storage Technologies' if 'storage' in tech_var else 'Fuel Cells / Hydrogen'
    df_rdd = df_rdd.fillna(0)
    df_rdd = df_rdd[df_rdd['Year'] < 2019]
    china = df_rdd[df_rdd['Country'] == 'China'][['Year', tech_var]]
    japan = df_rdd[df_rdd['Country'] == 'Japan'][['Year', tech_var]]
    korea = df_rdd[df_rdd['Country'] == 'Korea'][['Year', tech_var]]
    france = df_rdd[df_rdd['Country'] == 'France'][['Year', tech_var]]
    germany = df_rdd[df_rdd['Country'] == 'Germany'][['Year', tech_var]]
    uk = df_rdd[df_rdd['Country'] == 'UK'][['Year', tech_var]]
    usa = df_rdd[df_rdd['Country'] == 'USA'][['Year', tech_var]]
    labels = ['China', 'Japan', 'Korea', 'France', 'Germany', 'UK', 'USA']
    plt.stackplot(china['Year'], china[tech_var], japan[tech_var], korea[tech_var], france[tech_var], germany[tech_var],
                  uk[tech_var], usa[tech_var], labels=labels)
    legend = plt.legend(loc='upper left')
    legend.set_title(tech_var2)
    legend.get_title().set_fontweight('bold')
    plt.ylabel('2018 Million USD')
    plt.savefig(PATHS.figures / f'mainfigures/{figurename}.png', bbox_inches='tight')
    plt.savefig(PATHS.figures / f'mainfigures/{figurename}.pdf', bbox_inches='tight')
    plt.close()


def plotting_meanOEM_patent_and_policyexposure_onsamegraph():
    dfoemyear_policy = pd.read_csv(PATHS.dropbox / 'Data_outputted/D_Policy/firm_year_policy_exposure.csv')
    dfoemyear_patenting = reading_datasets.read_oem_firmlevel_panel()
    maskYears = dfoemyear_patenting['earliest_filing_year'].isin(range(1990, 2016))
    data = dfoemyear_patenting[maskYears].groupby('earliest_filing_year')[['Count_Bat_excl','Count_FC_excl']].mean()
    dataFC = pd.DataFrame(data['Count_FC_excl'])
    dataFC['RDD'] = dfoemyear_policy.groupby('Year')['fchydrogen_RDexposure'].mean()
    dataFC['Strategy'] = dfoemyear_policy.groupby('Year')['strat_fc_exposure'].mean()
    # FC FIGURE
    fig, ax1 = plt.subplots()
    ax1.plot(dataFC['Count_FC_excl'], label='Patent Count', color=dict_var_colors['Count_FC'][1], linewidth=5)
    ax1.set(ylabel='Patent Count', xlabel='Years')
    ax2 = ax1.twinx()
    ax2.plot(dataFC['RDD'], label='Public RD&D Funding', color=dict_var_colors['Count_FC'][1], linewidth=3)
    ax2.set_ylabel('Public RD&D Funding')
    ax3 = ax1.twinx()
    ax3.spines['right'].set_position(('outward', 60))
    ax3.plot(dataFC['Strategy'], label='Strategic Orientation', color=dict_var_colors['Count_FC'][1], linewidth=2, linestyle='--')
    ax3.set_ylabel('Strategic Orientation')
    # Add a legend
    h1, l1 = ax1.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    h3, l3 = ax3.get_legend_handles_labels()
    fig.tight_layout()
    legend = ax1.legend(h1 + h2 + h3, l1 + l2 + l3, loc="upper left", ncol=1, frameon=False)
    legend.set_title("Fuel Cells")
    title = legend.get_title()
    title.set_fontweight('bold')
    fig.savefig(PATHS.figures / f'mainfigures/FC_meanOEM_patent_and_policy_exposure.png', bbox_inches='tight')
    fig.savefig(PATHS.figures / f'mainfigures/FC_meanOEM_patent_and_policy_exposure.pdf', bbox_inches='tight')
    plt.close()
    # BEV FIGURE
    dataBEV = pd.DataFrame(data['Count_Bat_excl'])
    dataBEV['RDD'] = dfoemyear_policy.groupby('Year')['otherstorage_RDexposure'].mean()
    dataBEV['Strategy'] = dfoemyear_policy.groupby('Year')['strat_bev_exposure'].mean()
    fig, ax1 = plt.subplots()
    ax1.plot(dataBEV['Count_Bat_excl'], label='Patent Count', color=dict_var_colors['Count_Bat'][1], linewidth=5)
    ax1.set(ylabel='Patent Count', xlabel='Years')
    ax2 = ax1.twinx()
    ax2.plot(dataBEV['RDD'], label='Public RD&D Funding', color=dict_var_colors['Count_Bat'][1], linewidth=3)
    ax2.set_ylabel('Public RD&D Funding')
    ax3 = ax1.twinx()
    ax3.spines['right'].set_position(('outward', 60))
    ax3.plot(dataBEV['Strategy'], label='Strategic Orientation', color=dict_var_colors['Count_Bat'][1], linewidth=2, linestyle='--')
    ax3.set_ylabel('Strategic Orientation')
    fig.tight_layout()
    h1, l1 = ax1.get_legend_handles_labels()
    h2, l2 = ax2.get_legend_handles_labels()
    h3, l3 = ax3.get_legend_handles_labels()
    legend = ax1.legend(h1 + h2 + h3, l1 + l2 + l3, loc="upper left", ncol=1, frameon=False)
    legend.set_title("Battery")
    title = legend.get_title()
    title.set_fontweight('bold')
    fig.savefig(PATHS.figures / f'mainfigures/BEV_meanOEM_patent_and_policy_exposure.png', bbox_inches='tight')
    fig.savefig(PATHS.figures / f'mainfigures/BEV_meanOEM_patent_and_policy_exposure.pdf', bbox_inches='tight')
    plt.close()



def plot_bat_fc_patenting_bysector():
    df_batfc_fam = pd.read_csv(PATHS.dropbox / 'Data_outputted/C_PatentVariables/Families_Bat_FC_naics_info.csv')
    df_batfc_fam['pat_firm_id'] = df_batfc_fam['pid'].astype(str) + '_' + df_batfc_fam['fid'].astype(str)
    maskyears = df_batfc_fam['earliest_filing_year'].isin(range(1990, 2016))
    maskBAT = df_batfc_fam['Sub-sector_exclusive'] == 'batteries'
    maskFC = df_batfc_fam['Sub-sector_exclusive'] == 'fuel cells'
    pal2 = sns.color_palette('Greys')
    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
    for ax, mask in zip([ax1, ax2], [maskFC, maskBAT]):
        # MOTOR VEHICLE
        maskMotor = df_batfc_fam['MotorVehicle'].notnull() & (df_batfc_fam['MotorVehicle'] > 0)
        maskOEMsorSubsi = df_batfc_fam['OEMorSubsidiary'].notnull() & (df_batfc_fam['OEMorSubsidiary'] > 0)
        masksector = maskMotor | maskOEMsorSubsi
        data1 = df_batfc_fam[mask & maskyears & masksector].groupby('earliest_filing_year')['pat_firm_id'].nunique()
        ax.plot(data1, label='Motor Vehicle', color=pal2[-1], linewidth=3)
        # OTHER
        data2 = df_batfc_fam[mask & maskyears].groupby('earliest_filing_year')['pat_firm_id'].nunique()
        ax.set_ylim(0, 6500)
        ax_right = ax.twinx()
        data3 = 100 * data1 / data2
        ax_right.plot(data3, label='Percent of Total from Motor Vehicle', color=pal2[-1], linewidth=2, linestyle='--')
        ax_right.set_ylim(0, 40)
        ax_right.set_ylabel('Percent from Motor Vehicle (%)')
        # ELECTRONICS
        masksector = df_batfc_fam['Electronics'].notnull() & (df_batfc_fam['Electronics'] > 0)
        data = df_batfc_fam[mask & maskyears & masksector].groupby('earliest_filing_year')['pat_firm_id'].nunique()
        ax.plot(data, label='Electronics', color=pal[-1], linewidth=3)
        # MACHINERY
        masksector = df_batfc_fam['MachineryChemical'].notnull() & (df_batfc_fam['MachineryChemical'] > 0)
        data = df_batfc_fam[mask & maskyears & masksector].groupby('earliest_filing_year')['pat_firm_id'].nunique()
        ax.plot(data, label='Machinery and Chemical Manufacturing', color=pal[-2], linewidth=2)
        # TRANSPORT
        masksector = df_batfc_fam['OtherTransport'].notnull() & (df_batfc_fam['OtherTransport'] > 0)
        data = df_batfc_fam[mask & maskyears & masksector].groupby('earliest_filing_year')['pat_firm_id'].nunique()
        ax.plot(data, label='Other Transport', color=pal[-3], linewidth=2)
        ax.set_xlabel('Year')
        ax.set_ylabel('Number of Patent Families')
        h1, l1 = ax.get_legend_handles_labels()
        h2, l2 = ax_right.get_legend_handles_labels()
    plt.subplots_adjust(bottom=0.15, wspace=.4)
    fig.legend(h2 + h1, l2 + l1, loc='lower center', ncol=5, fontsize=12, fancybox=True, frameon=True, edgecolor='black', framealpha=.5, borderpad=.7)
    ax1.set_title('Fuel Cell Patents')
    ax2.set_title('Battery Patents')
    plt.savefig(PATHS.figures / 'mainfigures' / 'BatFC_Patenting_bysector.pdf', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / 'BatFC_Patenting_bysector.png', bbox_inches='tight')
    # ADDING battery costs
    price_series = pd.read_csv(PATHS.other / 'LiIon_price_series.csv')
    for year in [1992, 1996, 1998, 2000, 2004, 2009, 2015]:
        priceyear = int(price_series.loc[price_series['Year'] == year, 'Price'].values[0])
        ax2.scatter(year, priceyear, marker='x', color='red')
        ax2.annotate(f'${priceyear}/kWh', [year-2, priceyear + 120], fontsize='x-small', color='red')
    # ADDING FC costs
    FCcosts = getting_FC_costs()
    year = 1996
    priceyear = int(FCcosts.loc[FCcosts['Year'] == year, 'Price'].values[0])
    ax1.scatter(year, 6400, marker='x', color='red')
    ax1.annotate(f'${priceyear}/kW', [year - 1, 6000 + 120], fontsize='x-small', color='red')
    for year in [2000, 2006, 2009, 2015]:
        priceyear = int(FCcosts.loc[FCcosts['Year'] == year, 'Price'].values[0])
        ax1.scatter(year, 10*priceyear, marker='x', color='red')
        ax1.annotate(f'${priceyear}/kW', [year-1, 10*priceyear + 120], fontsize='x-small', color='red')
    plt.savefig(PATHS.figures / 'mainfigures' / 'BatFC_Patenting_bysector.pdf', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / 'BatFC_Patenting_bysector.png', bbox_inches='tight')
    plt.close()



def stackplot_activesupplierpatenting_bytype():
    dfsupplieryear = reading_datasets.read_supplier_firmlevel_panel()
    beg_year, end_year = 1990, 2016
    maskActive = dfsupplieryear['Active'] == 1
    maskYears = (dfsupplieryear['earliest_filing_year'] >= beg_year) & (dfsupplieryear['earliest_filing_year'] < end_year)
    data = dfsupplieryear[maskActive & maskYears].groupby('earliest_filing_year').sum()
    # Now get data for stacked areas
    """ we're assuming minimal double patenting by firms as we sum across firms"""
    maskYears = (dfsupplieryear['earliest_filing_year'] >= 2003) & (dfsupplieryear['earliest_filing_year'] < 2016)
    maskActive20032017 = (dfsupplieryear['Active'] == 1) & maskYears
    autosectorMask = dfsupplieryear['4digitNAICS'].notnull() & (dfsupplieryear['4digitNAICS'].str.contains('3361|3362|3363', regex=True)) & maskActive20032017
    oldguardMask = (dfsupplieryear['oldguard'] == 1) & (~autosectorMask) & maskActive20032017
    newguardMask = (dfsupplieryear['oldguard'] == 0) & (~autosectorMask) & maskActive20032017
    cols = ['Count_Bat_excl']
    autosuppliers_innovation_ts = dfsupplieryear[autosectorMask].groupby(['earliest_filing_year'])[cols].sum().reset_index().rename(columns={c: 'automotive_'+c for c in cols})
    oldguard_supp_ts = dfsupplieryear[oldguardMask].groupby(['earliest_filing_year'])[cols].sum().reset_index().rename(columns = {c: 'oldguard_'+c for c in cols})
    newguard_supp_ts = dfsupplieryear[newguardMask].groupby(['earliest_filing_year'])[cols].sum().reset_index().rename(columns = {c: 'newguard_'+c for c in cols})
    active_supp_ts = dfsupplieryear[maskActive20032017].groupby(['earliest_filing_year'])[cols].sum().reset_index()
    maskYears = (active_supp_ts['earliest_filing_year'] >= 2003) & (active_supp_ts['earliest_filing_year'] < 2016)
    supp_ts_bygroup = active_supp_ts[maskYears].merge(autosuppliers_innovation_ts, on='earliest_filing_year', how='left')
    supp_ts_bygroup = supp_ts_bygroup.merge(oldguard_supp_ts, on='earliest_filing_year', how='left')
    supp_ts_bygroup = supp_ts_bygroup.merge(newguard_supp_ts, on='earliest_filing_year', how='left')
    supp_ts_bygroup.fillna(0, inplace=True)
    # PLOT FIGURE
    pal2 = sns.color_palette('Blues')
    plt.plot(data['Count_FC_excl'], label='Fuel Cells Patents', color=dict_var_colors['Count_FC_excl'][1], linewidth=5)
    plt.plot(data['Count_Bat_excl'], label='Battery Patents:', color=dict_var_colors['Count_Bat_excl'][1], linewidth=5)
    plt.stackplot(supp_ts_bygroup['earliest_filing_year'],
                  supp_ts_bygroup['automotive_Count_Bat_excl'],
                  supp_ts_bygroup['oldguard_Count_Bat_excl'],
                  supp_ts_bygroup['newguard_Count_Bat_excl'],
                  labels=['  from suppliers in Motor Vehicles', '  from outside Motor Vehicles - Old', '  from outside Motor Vehicles - New'],
                  colors=[pal2[-6], pal2[-4], pal2[-2]], linewidth=0)
    plt.ylabel('Number of Patent Families')
    plt.legend(loc='upper left', ncol=1)
    plt.savefig(PATHS.figures / 'mainfigures' / 'activesupplierspatenting_battery_stackplot_bytypeofsuppliers.png', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / 'activesupplierspatenting_battery_stackplot_bytypeofsuppliers.pdf', bbox_inches='tight')
    plt.close()



def plot_activesuppliers_stocks():
    oemsupplierlinks_supplierstocks = reading_datasets.get_oem_supplier_activelinks_with_supplierstocks(balanced=False)
    # we need to keep only active links.
    oemsupplierlinks_supplierstocks = oemsupplierlinks_supplierstocks[oemsupplierlinks_supplierstocks['Active']]
    new_suppliers = oemsupplierlinks_supplierstocks[oemsupplierlinks_supplierstocks['Years_since_firstactive'] == 0]
    preexisting_suppliers = oemsupplierlinks_supplierstocks[oemsupplierlinks_supplierstocks['Years_since_firstactive'] > 0]
    # PLOT
    tech = 'Bat'
    BATmean_new_suppliers = new_suppliers.groupby('Year')[f'Stock_{tech}'].mean()
    BATmean_preexisting_suppliers = preexisting_suppliers.groupby('Year')[f'Stock_{tech}'].mean()
    tech = 'FC'
    FCmean_new_suppliers = new_suppliers.groupby('Year')[f'Stock_{tech}'].mean()
    FCmean_preexisting_suppliers = preexisting_suppliers.groupby('Year')[f'Stock_{tech}'].mean()
    fig, ax = plt.subplots()
    plt.plot(BATmean_new_suppliers, label='Battery Stock, New Suppliers', color=dict_var_colors['Count_Bat'][1], linewidth=3)
    plt.plot(BATmean_preexisting_suppliers, label='Battery Stock, Pre-existing Suppliers', color=dict_var_colors['Count_Bat'][1], linewidth=3, linestyle='--')
    plt.plot(FCmean_new_suppliers, label='Fuel Cell Stock, New Suppliers', color=dict_var_colors['Count_FC'][1], linewidth=3)
    plt.plot(FCmean_preexisting_suppliers, label='Fuel Cell Stock, Pre-existing Suppliers', color=dict_var_colors['Count_FC'][1], linewidth=3, linestyle='--')
    plt.legend(ncol=1)
    plt.xlabel('Year')
    plt.ylabel('Mean Patent Stock of Active Suppliers')
    plt.savefig(PATHS.figures / 'mainfigures' / 'activesuppliers_stocks_new_vs_existing.png', bbox_inches='tight')
    plt.savefig(PATHS.figures / 'mainfigures' / 'activesuppliers_stocks_new_vs_existing.pdf', bbox_inches='tight')
    plt.close()


def getting_FC_costs():
    # FC costs
    FCcosts = {}
    # https://www-sciencedirect-com.gate3.library.lse.ac.uk/science/article/pii/S0360319996001759
    # The fuel cell stacksare currently being produced on a one-by-one basis as prototypes, and their production cost is approximately
    # $3OOO/kW
    FCcosts[1996] = 3000
    # 2000: https://afdc.energy.gov/files/pdfs/baseline_cost_model.pdf
    # $300/kW
    FCcosts[2000] = 300
    # https://www.hydrogen.energy.gov/pdfs/htac_oct1410_overview.pdf
    FCcosts[2002] = 275
    #  2006 to 2017
    # https://www.hydrogen.energy.gov/pdfs/17007_fuel_cell_system_cost_2017.pdf
    FCcosts[2006] = 124
    FCcosts[2007] = 106
    FCcosts[2008] = 81
    FCcosts[2009] = 69
    FCcosts[2010] = 59
    FCcosts[2011] = 57
    FCcosts[2012] = 55
    FCcosts[2013] = 55
    FCcosts[2014] = 55
    FCcosts[2015] = 53
    FCcosts[2016] = 53
    FCcosts[2017] = 45
    FCcosts = pd.Series(FCcosts).reset_index().rename(columns={'index': 'Year', 0: 'Price'})
    return FCcosts




def getting_FC_costs():
    # FC costs
    FCcosts = {}
    # a = 'Source: https://www-sciencedirect-com.gate3.library.lse.ac.uk/science/article/pii/S0360319996001759'
    a = 'Barbir, F., and T. Gómez. 1997. “Efficiency and Economics of Proton Exchange Membrane (PEM) Fuel Cells.” International Journal of Hydrogen Energy 22 (10): 1027–37.'
    # The fuel cell stacksare currently being produced on a one-by-one basis as prototypes, and their production cost is approximately
    # $3OOO/kW
    FCcosts[1996] = 3000
    # 2000:
    # b = 'Source: https://afdc.energy.gov/files/pdfs/baseline_cost_model.pdf'
    b = 'US Department of Energy. 2000. “Cost Analysis of Fuel Cell.” https://afdc.energy.gov/files/pdfs/baseline_cost_model.pdf.'
    # $300/kW
    FCcosts[2000] = 300
    # c = 'Source: https://www.hydrogen.energy.gov/pdfs/htac_oct1410_overview.pdf'
    c = 'US Department of Energy. 2010. “Overview of Hydrogen and Fuel Cell Activities.” https://www.hydrogen.energy.gov/pdfs/htac_oct1410_overview.pdf.'
    FCcosts[2002] = 275
    # 2006 to 2017
    # d = 'Source: https://www.hydrogen.energy.gov/pdfs/17007_fuel_cell_system_cost_2017.pdf'
    d = 'US Department of Energy. 2017. “Fuel Cell Technologies Office Record 17007: Fuel Cell System Cost.” https://www.hydrogen.energy.gov/pdfs/17007_fuel_cell_system_cost_2017.pdf.'
    FCcosts[2006] = 124
    FCcosts[2007] = 106
    FCcosts[2008] = 81
    FCcosts[2009] = 69
    FCcosts[2010] = 59
    FCcosts[2011] = 57
    FCcosts[2012] = 55
    FCcosts[2013] = 55
    FCcosts[2014] = 55
    FCcosts[2015] = 53
    FCcosts[2016] = 53
    FCcosts[2017] = 45
    FCcosts = pd.Series(FCcosts).reset_index().rename(columns={'index': 'Year', 0: 'Price'})
    # Making a table for the appendix
    data = FCcosts.iloc[:4, :]
    data = data.astype(str)
    data['Year'] = data['Year'].replace('2006', '2006-2017')
    data['Source'] = np.nan
    data.loc[0, 'Source'] = a
    data.loc[1, 'Source'] = b
    data.loc[2, 'Source'] = c
    data.loc[3, 'Source'] = d
    data = data.drop(columns=['Price'])
    pd.set_option('display.max_colwidth', None)
    # data_tex = data.to_latex(index=False)
    data_tex = data.to_latex(index=False, column_format='cL{20cm}')
    data_tex = data_tex.replace(r'\\', r'\\ \hline')
    data_tex = data_tex.replace('\\hline\n\\midrule', '\midrule ')
    data_tex = data_tex.replace('\\hline\n\\bottomrule', '\\bottomrule')
    data_tex = data_tex.replace('Year',  '\\textbf{Year}')
    data_tex = data_tex.replace('Source',  '\\textbf{Source}')
    with open(PATHS.tables / 'fc_prices.tex', "w") as f:
        f.write(data_tex)
    return FCcosts
